package pe.com.hermes.hermetic.web.controller.general;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttributes;

import pe.com.hermes.hermetic.beans.ClienteBean;
import pe.com.hermes.hermetic.negocio.service.ClienteService;
import pe.com.hermes.hermetic.negocio.service.HermeticFacade;
import pe.com.hermes.hermetic.negocio.ultil.Util;
import pe.com.hermes.hermetic.web.controller.base.IController;
import pe.com.hermes.hermetic.web.forms.SelecBancoForm;
import pe.com.hermes.hermetic.web.forms.SelecPuntoForm;

@Controller
@RequestMapping("/selecBanco.html")
@SessionAttributes(value={"form"})
public class SeleccionarBancoController implements IController{
  protected final static Logger logger = Logger.getLogger(SeleccionarBancoController.class);
  @Autowired
  private HermeticFacade servicioHermetic;
  @Autowired
  private ClienteService clienteService;
  
  @RequestMapping(method={RequestMethod.GET})    
  protected String showForm(ModelMap model,HttpServletRequest request)throws Exception{
      try {
          logger.info(this.getClass().toString()+" "+"metodo: GET");
          SelecBancoForm form = new SelecBancoForm();
          
          String v_cliente=request.getParameter("v_cliente");
          String v_codCliente = request.getParameter("v_CodClie");
          form.setV_cliente(v_cliente);
          if(v_cliente.equals("1"))
          {
            String listCodClies="";
            if (v_codCliente != null ){
              listCodClies = v_codCliente;
            }else{
                String[] codClies=(String[])request.getSession(false).getAttribute("chksClieCorp");
                for(int i=0;i<codClies.length;i++){
                    if(codClies[i]!=null){
                      if(i==0)
                          listCodClies=codClies[i];
                      else
                          listCodClies=listCodClies+","+codClies[i];
                    }
                }
            }   
            form.setListCodClientes(listCodClies);
          }
          else
           form.setListCodClientes((String)request.getSession(false).getAttribute("listClie"));
          
          
          form.setCodSucuHtb((String)request.getSession(false).getAttribute("sucursal"));
          List<ClienteBean> listBancos = new ArrayList();        
          listBancos = clienteService.getListBancByClie(form.getListCodClientes(), "");
          
          //asigno los valores de las cuentas seleccionadas en session
          String[] chksBanco = (String[])request.getSession(false).getAttribute("chksBanco");
          listBancos = Util.setChksSession(chksBanco, listBancos);   
          
          form.setListBancos(listBancos);
          request.getSession(false).setAttribute("listBancos",listBancos);
          model.put("listBancos",listBancos);
          model.put(FORM_KEY,form);
          return FORM_SELECT_BANCO;
      }
      catch (Exception e) {
          logger.error(e);
          return FORM_ERROR_POPUP_VIEW;
      }
  }
  
  @RequestMapping(params={"accion=buscarBanco","desBanco","v_cliente"}) 
  protected String buscarBanco(@RequestParam("desBanco") String desBanco ,@RequestParam("v_cliente") String v_cliente ,ModelMap model,HttpServletRequest request)throws Exception{
              logger.info(this.getClass().toString()+" "+"metodo: GET");
      SelecBancoForm form = new SelecBancoForm();
      form.setCliente((String)request.getSession(false).getAttribute("cliente"));        
      form.setCodSucuHtb((String)request.getSession(false).getAttribute("sucursal"));
      String[] chksBanco = (String[])request.getSession(false).getAttribute("chksBanco");
      List listBancos = new ArrayList();        
      
      if(v_cliente.equals("1"))
      {
        String listCodClies="";
        String[] codClies=(String[])request.getSession(false).getAttribute("chksClieCorp");
        for(int i=0; i < codClies.length; i++)        {
              if(codClies[i]!=null){
                if(i==0)
                    listCodClies=codClies[i];
                else
                    listCodClies=listCodClies+","+codClies[i];
              }
        }
        form.setListCodClientes(listCodClies);
      }
      else
       form.setListCodClientes((String)request.getSession(false).getAttribute("listClie"));
      
      listBancos = clienteService.getListBancByClie(form.getListCodClientes(), desBanco);
      listBancos = Util.setChksSession(chksBanco,listBancos);
      form.setListBancos(listBancos);
      if(desBanco.equals(""))
          request.getSession(false).setAttribute("listBancos",listBancos);
      model.put("listBancos",listBancos);
      model.put(FORM_KEY,form);
      return FORM_SELECT_BANCO;
  }
  
  
  
  @RequestMapping(params={"accion=searchDesBanco"}) 
  protected @ResponseBody String[] searchDesBanco(HttpServletRequest request)throws Exception{        
      logger.info(this.getClass().toString()+" "+"metodo: searchDesBanco");        
      List listModulos = (List)request.getSession(false).getAttribute("listBancos");
      String[] arrayModulos = new String[listModulos.size()];
      for(int i=0;i<listModulos.size();i++){
          ClienteBean pBean=(ClienteBean)listModulos.get(i);
          arrayModulos[i] = pBean.getNomClie();
      }
      return arrayModulos;
  }
  
  @RequestMapping(params={"accion=selectCodBanco","codBanco"}) 
  protected @ResponseBody String[] selectCodBanco(@RequestParam("codBanco") String codBanco,@ModelAttribute(FORM_KEY) SelecBancoForm form,HttpServletRequest request)throws Exception{        
      logger.info(this.getClass().toString()+" "+"metodo: selectCodBanco");
      String[] chksBanco = (String[])request.getSession(false).getAttribute("chksBanco");
      if(("").equals(codBanco))
          return chksBanco;
      if(chksBanco!=null)
          for(int i=0;i<chksBanco.length;i++){                
              if(chksBanco[i]!=null&&chksBanco[i].equals(codBanco)){
                  break;
              }
              if(chksBanco[i]==null){
                  chksBanco[i] = codBanco;
                  break;
              }
          }
      else{
          chksBanco= new String[1000];
          chksBanco[0]=codBanco;
      }
      request.getSession(false).setAttribute("chksBanco",chksBanco);        
      request.getSession(false).setAttribute("chksBancoTipClie",chksBanco);  
      return chksBanco;
  }
  
  @RequestMapping(params={"accion=deselectCodBanco","codBanco"}) 
  protected @ResponseBody String[] deselectCodBanco(@RequestParam("codBanco") String codBanco,@ModelAttribute(FORM_KEY) SelecBancoForm form,HttpServletRequest request)throws Exception{        
      logger.info(this.getClass().toString()+" "+"metodo: deselectCodBanco");        
      String[] chksBanco = (String[])request.getSession(false).getAttribute("chksBanco");

      if(chksBanco!=null && chksBanco.length > 0)
          for(int i=0;i<chksBanco.length;i++){
              if(chksBanco[i]!=null && chksBanco[i].equals(codBanco)){
                  chksBanco[i] = null;
                  break;
              }
          }            
      
      request.getSession(false).setAttribute("chksBanco",chksBanco);     
      request.getSession(false).setAttribute("chksBancoTipClie",chksBanco); 
      return chksBanco;
  }        
  
  @RequestMapping(params={"accion=seleccionarBancos"})
  protected void seleccionarBancos(ModelMap model,@ModelAttribute(FORM_KEY) SelecBancoForm form,HttpServletRequest request)throws Exception{
      logger.info("seleccionarBancos");
      String[] _chk = request.getParameterValues("_chk");
      request.getSession(false).setAttribute("_chk",_chk);
  } 

  @RequestMapping(params={"accion=selectTodos","codTodos"})
  
  protected String selectTodos(@RequestParam("codTodos") boolean codTodos ,ModelMap model,HttpServletRequest request)throws Exception{
      logger.info(this.getClass().toString()+" "+"metodo: GET");
      SelecBancoForm form = (SelecBancoForm)model.get("form");//new SelecCuentaForm();
      
      //Asigno el check a todos los elenmentos de la lista Cuenta        
      List listBancos = form.getListBancos();
      listBancos = Util.setChksTodos(codTodos, listBancos);
      form.setListBancos(listBancos);
      
      //Subo a session los todos los Checks Cuenta
      if (codTodos) {
          String[] chksBanco = Util.listToStringArray(listBancos);
          request.getSession(false).setAttribute("chksBanco",chksBanco);
          request.getSession(false).setAttribute("chksBancoTipClie",chksBanco);
      }else {
          request.getSession(false).setAttribute("chksBanco",null);
          request.getSession(false).setAttribute("chksBancoTipClie",null);
      }
      
      request.getSession(false).setAttribute("listBancos",listBancos);
      model.put("listBancos",listBancos);
      model.put(FORM_KEY,form);
      return FORM_SELECT_BANCO;
  }
  
  @RequestMapping(params={"accion=limpiarBancos"}) 
  protected String limpiarBancos(HttpServletRequest request)throws Exception{
      logger.info(this.getClass().toString()+" "+"metodo: GET");
      HttpSession session = request.getSession(false);        
      session.setAttribute("chksBanco",null);
      ModelMap model = new ModelMap();
      model.put(FORM_KEY, new SelecBancoForm());
      return FORM_SELECT_BANCO;
  }
}
